﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml.Xsl;

namespace Landscape.Compilers {
    class DotNetCompiler : IXSLCompiler {
        public object Compile(System.Xml.XmlDocument stylesheet) {
            XslCompiledTransform xsltCompiled = new XslCompiledTransform();
            xsltCompiled.Load(stylesheet, new XsltSettings(true, true), new TemplateXmlUrlResolver(Context.Library.includePaths));
            return xsltCompiled;
        }

        public System.IO.Stream Transform(System.Xml.XPath.XPathDocument dataSource, object compiledTransform, IDictionary<string, object> templateParams) {
            XslCompiledTransform transformer = (XslCompiledTransform)compiledTransform;
            XsltArgumentList xsltArgs = new XsltArgumentList();
            xsltArgs.AddExtensionObject("urn:landscape", new XSLT.Library(ref Renderer.SessionSettings));

            Dictionary<string, object> xsltExtensions = new Dictionary<string, object>(Renderer.XSLTExtensions);

            if (xsltExtensions.Count > 0) {
                foreach (KeyValuePair<string, object> ext in xsltExtensions) {
                    xsltArgs.AddExtensionObject(ext.Key, ext.Value);
                }
            }

            // add specified params
            if (templateParams != null && templateParams.Count > 0) {
                foreach (KeyValuePair<string, object> xslParam in templateParams) {
                    xsltArgs.AddParam(xslParam.Key, "", xslParam.Value);
                }
            }

            MemoryStream result = new MemoryStream();
            transformer.Transform(dataSource, xsltArgs, result);
            result.Position = 0;
            return result;
        }
    }
}
